import { ApiCall } from 'tsrpc'
import { ReqExportConfigs, ResExportConfigs } from '../shared/api_config_editor/PtlExportConfigs'

export default async function (call: ApiCall<ReqExportConfigs, ResExportConfigs>) {
    try {
        const { types, options } = call.req
        
        const fs = require('fs')
        const path = require('path')
        const configDir = path.resolve(__dirname, '../core/config')
        const exportDir = path.resolve(__dirname, '../exports')
        
        // 确保导出目录存在
        if (!fs.existsSync(exportDir)) {
            fs.mkdirSync(exportDir, { recursive: true })
        }
        
        // 收集要导出的配置数据
        const exportData: Record<string, any[]> = {}
        
        for (const type of types) {
            let configData: any[] = []
            
            switch (type) {
                case 'equipment':
                    const { configManager } = require('../config/ConfigManager')
                    configData = configManager.getAllEquipmentTemplates()
                    break
                    
                case 'skill':
                    // 需要实现getAllSkills方法
                    configData = []
                    break
                    
                default:
                    // 从文件中读取其他配置
                    const files = fs.readdirSync(configDir)
                    const matchingFile = files.find((file: string) => 
                        file.startsWith(type + '_') && file.endsWith('.json')
                    )
                    
                    if (matchingFile) {
                        try {
                            const filePath = path.join(configDir, matchingFile)
                            const content = fs.readFileSync(filePath, 'utf-8')
                            const jsonData = JSON.parse(content)
                            configData = Array.isArray(jsonData) ? jsonData : [jsonData]
                        } catch (error) {
                            console.warn(`Failed to read config file for type ${type}:`, error)
                        }
                    }
            }
            
            if (configData.length > 0) {
                exportData[type] = configData
            }
        }
        
        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
        const typeStr = types.length === 1 ? types[0] : 'multiple'
        const filename = `config_export_${typeStr}_${timestamp}`
        
        let exportFilePath: string
        let downloadUrl: string
        let fileSize: number
        
        switch (options.format) {
            case 'json':
                exportFilePath = path.join(exportDir, `${filename}.json`)
                
                const jsonData = types.length === 1 ? exportData[types[0]] : exportData
                const jsonContent = options.minify 
                    ? JSON.stringify(jsonData)
                    : JSON.stringify(jsonData, null, 2)
                
                fs.writeFileSync(exportFilePath, jsonContent)
                break
                
            case 'yaml':
                exportFilePath = path.join(exportDir, `${filename}.yaml`)
                
                // 简单的YAML导出（需要yaml库，这里简化实现）
                let yamlContent = '# Bot Server Configuration Export\n'
                yamlContent += `# Generated at: ${new Date().toISOString()}\n\n`
                
                for (const [type, data] of Object.entries(exportData)) {
                    yamlContent += `${type}:\n`
                    yamlContent += `  count: ${data.length}\n`
                    yamlContent += `  data:\n`
                    for (const item of data) {
                        yamlContent += `    - id: "${item.id || item.skillId || item.name}"\n`
                        yamlContent += `      name: "${item.name}"\n`
                        // 这里可以添加更多字段的YAML格式化
                    }
                    yamlContent += '\n'
                }
                
                fs.writeFileSync(exportFilePath, yamlContent)
                break
                
            case 'typescript':
                exportFilePath = path.join(exportDir, `${filename}.ts`)
                
                let tsContent = '// Bot Server Configuration Export\n'
                tsContent += `// Generated at: ${new Date().toISOString()}\n\n`
                
                for (const [type, data] of Object.entries(exportData)) {
                    const typeName = type.charAt(0).toUpperCase() + type.slice(1) + 'Config'
                    tsContent += `export const ${type}Configs: ${typeName}[] = `
                    tsContent += JSON.stringify(data, null, 2)
                    tsContent += ';\n\n'
                }
                
                fs.writeFileSync(exportFilePath, tsContent)
                break
                
            case 'xlsx':
                exportFilePath = path.join(exportDir, `${filename}.xlsx`)
                
                // Excel导出（需要xlsx库，这里简化实现）
                // 创建一个简单的CSV格式作为替代
                const csvPath = path.join(exportDir, `${filename}.csv`)
                let csvContent = ''
                
                for (const [type, data] of Object.entries(exportData)) {
                    csvContent += `配置类型,${type}\n`
                    csvContent += `配置数量,${data.length}\n\n`
                    
                    if (data.length > 0) {
                        // 表头
                        const headers = Object.keys(data[0])
                        csvContent += headers.join(',') + '\n'
                        
                        // 数据行
                        for (const item of data) {
                            const values = headers.map(header => {
                                const value = item[header]
                                if (typeof value === 'object') {
                                    return `"${JSON.stringify(value).replace(/"/g, '""')}"`
                                }
                                return `"${String(value || '').replace(/"/g, '""')}"`
                            })
                            csvContent += values.join(',') + '\n'
                        }
                    }
                    csvContent += '\n'
                }
                
                fs.writeFileSync(csvPath, csvContent)
                exportFilePath = csvPath
                break
                
            default:
                call.error(`不支持的导出格式: ${options.format}`)
                return
        }
        
        // 获取文件大小
        const stats = fs.statSync(exportFilePath)
        fileSize = stats.size
        
        // 生成下载URL（相对于exports目录）
        const relativePath = path.relative(exportDir, exportFilePath)
        downloadUrl = `/exports/${relativePath}`
        
        call.succ({
            data: {
                filename: path.basename(exportFilePath),
                downloadUrl,
                fileSize
            }
        })
        
    } catch (error) {
        console.error('Failed to export configs:', error)
        call.error('导出配置失败', {
            errors: [(error as any).message]
        })
    }
}
